package cn.wen233.iocdemo.api;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.wen233.iocdemo.common.api.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 主机相关接口
 *
 * @author wenei
 * @date 2021-06-26 17:43
 */
@RestController
public class HostApi {

    private final String unKnown = "unKnown";

    private static final Logger log = LoggerFactory.getLogger(HostApi.class);

    @GetMapping("/getIp")
    public R<?> getHostIp(HttpServletRequest request) {
        String XFor = request.getHeader("X-Forwarded-For");
        log.info("X-Forwarded-For信息：{}", XFor);
        if (!StrUtil.isEmpty(XFor) && unKnown.equalsIgnoreCase(XFor)) {
            int index = XFor.indexOf(",");
            if (index != -1) {
                return R.success(XFor.substring(0, index));
            } else {
                return R.success(XFor);
            }
        }
        String XIp = request.getHeader("X-Real-IP");
        log.info("X-Real-IP信息：{}", XIp);
        if (isNotEmpty(XIp)) {
            return R.success(XIp);
        }
        if (isBlank(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
            log.info("Proxy-Client-IP信息：{}", XFor);
        }
        if (isBlank(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
            log.info("WL-Proxy-Client-IP信息：{}", XFor);
        }
        if (isBlank(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
            log.info("HTTP_CLIENT_IP信息：{}", XFor);
        }
        if (isBlank(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
            log.info("HTTP_X_FORWARDED_FOR信息：{}", XFor);
        }
        if (isBlank(XFor)) {
            XFor = request.getRemoteAddr();
            log.info("request.getRemoteAddr信息：{}", XFor);
        }
        return R.success(XFor);
    }

    private boolean isNotEmpty(String str) {
        return !StrUtil.isEmpty(str) && unKnown.equalsIgnoreCase(str);
    }

    private boolean isBlank(String str) {
        return StrUtil.isBlank(str) || unKnown.equalsIgnoreCase(str);
    }
}
